package com.WPMS;

import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Context;
import android.location.Location;
import android.net.wifi.ScanResult;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class WPMS extends ListActivity implements WMSSubscriber, WPSSubscriber 
{
	private static final int EXIT = 0;
	private static final String NO_DATA = "No Historical Data";
	

    private ArrayAdapter<String> mlistAdapter;
    
    private WiFiMappingSystem wms;
    
    private WiFiPositioningSystem wps;
    
    private ArrayList<String> positionData = new ArrayList<String>();
    
    
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        positionData.add(NO_DATA);
        mlistAdapter = new ArrayAdapter<String>(this, R.layout.list_item, positionData);
        setListAdapter(mlistAdapter);

        ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        createButtons();
    }
    
    
    public void createButtons() 
    {
    	//Register Buttons click listeners
	    Button WMSSButton = (Button)findViewById(R.id.WMSSButton);
	    WMSSButton.setOnClickListener(mWMSSButtonListener);
	    
	    Button WPSSButton = (Button)findViewById(R.id.WPSSButton);
	    WPSSButton.setOnClickListener(mWPSSButtonListener);
	    
	    Button clearButton = (Button)findViewById(R.id.clearButton);
	    clearButton.setOnClickListener(mClearButtonListener);   
    }
    
    
    ///////////////////////////////////////////////////////////////////////////
    // Menu
    ///////////////////////////////////////////////////////////////////////////
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	menu.add(0, EXIT, 0, "Exit");
    	return true;
    }
    
    public boolean onOptionsItemSelected (MenuItem item)
    {
    	switch (item.getItemId())
    	{
	    	case EXIT:
	    		//shutdown any tasks that may be running
	    		this.finish();
		    return true;
	    }
	    return false;
    }
    
    
    ///////////////////////////////////////////////////////////////////////////
    // Listeners
    ///////////////////////////////////////////////////////////////////////////
    private boolean WMSSStarted = false;
    private boolean WPSSStarted = false;
    
    private OnClickListener mClearButtonListener = new OnClickListener() 
    {
    	public void onClick(View v) 
    	{
    		positionData.clear();
    		positionData.add(NO_DATA);
    		mlistAdapter.notifyDataSetChanged();
    	}
    	
    };
    
    
    // Create an anonymous implementation of OnClickListener
    private OnClickListener mWMSSButtonListener = new OnClickListener() 
    {
        public void onClick(View v) 
        {
        	CharSequence ButtonText = ((TextView) v).getText();
        	String strButtonText = ButtonText.toString();
        
        	Context context = getApplicationContext();
        	int duration = Toast.LENGTH_SHORT;
        	Toast toast;
        	CharSequence toastText = null;
        	String newStrButtonText = null;
        	String currentTitleStr = null;
        	String historicalDataStr = null;
        	        	
        	// If Button was Start Mapping and Mapping is not currently running - Start Running
        	if(strButtonText.equals("Start Mapping") && !WMSSStarted)
        	{
        		WMSSStarted = true;
        		startWMSS();
        		
	        	//change text strings
        		newStrButtonText = "Stop Mapping";
        		currentTitleStr = "Current GPS Position";
        		historicalDataStr = "Current WiFi Access Points";
	        	
	        	if(!WPSSStarted)
	        	{
	        		toastText = "Running Mapping Application";
	        	}
	        	else
	        	{
	        		toastText = "Stopping Positioning Application and Running Mapping Application";
	        		stopWPSS();
	        		WPSSStarted = false;
	        		((Button)findViewById(R.id.WPSSButton)).setText("Start Positioning");
	        	}
	        // If Button was Stop Mapping and Mapping is running - Stop Running
        	}
        	else if(strButtonText.equals("Stop Mapping") && WMSSStarted)
        	{  
        		WMSSStarted = false;
        		stopWMSS();
        		
	        	//change text strings
	        	toastText = "Stopping Mapping Application";
	        	newStrButtonText = "Start Mapping";
        		currentTitleStr = "Current Position";
        		historicalDataStr = "Historical Data";
        	}
        	//show toast
        	toast = Toast.makeText(context, toastText, duration);
        	toast.show();
        	((Button)findViewById(R.id.WMSSButton)).setText(newStrButtonText);
        	((TextView)findViewById(R.id.currentTitle)).setText(currentTitleStr);
        	((TextView)findViewById(R.id.historicalTitle)).setText(historicalDataStr);
        }
    };
    
    
    private OnClickListener mWPSSButtonListener = new OnClickListener() 
    {
    	public void onClick(View v) 
    	{
        	CharSequence ButtonText = ((TextView) v).getText();
        	String strButtonText = ButtonText.toString();
        
        	Context context = getApplicationContext();
        	int duration = Toast.LENGTH_SHORT;
        	Toast toast;
        	CharSequence toastText = null;
        	String newStrButtonText = null;
        	String currentTitleStr = null;
        	String historicalDataStr = null;
        	
        	// If Button was Start Positioning and Positioning is not currently running - Start Running
        	if(strButtonText.equals("Start Positioning") && !WPSSStarted)
        	{
        		WPSSStarted = true;
        		startWPSS();
        		
	        	//change text strings
        		newStrButtonText = "Stop Positioning";
        		currentTitleStr = "Current GPS Position (Based on WiFi)";
        		historicalDataStr = "Historical Data";
	        	
	        	if(!WMSSStarted)
	        	{
	        		toastText = "Running Positioning Application";
	        	}
	        	else
	        	{
	        		toastText = "Stopping Mapping Application and Running Positioning Application";
	        		stopWMSS();
	        		WMSSStarted = false;
	        		((Button)findViewById(R.id.WMSSButton)).setText("Start Mapping");
	        	}
	        // If Button was Stop Positioning and Positioning is running - Stop Running
        	}
        	else if(strButtonText.equals("Stop Positioning") && WPSSStarted)
        	{  
        		WPSSStarted = false;
        		stopWPSS();
        		
	        	//change text strings
	        	toastText = "Stopping Positioning Application";
	        	newStrButtonText = "Start Positioning";
        		currentTitleStr = "Current GPS Position (Based on WiFi)";
        		historicalDataStr = "Historical Data";
        	}
        	//show toast
        	toast = Toast.makeText(context, toastText, duration);
        	toast.show();
        	((Button)findViewById(R.id.WPSSButton)).setText(newStrButtonText);
        	((TextView)findViewById(R.id.currentTitle)).setText(currentTitleStr);
        	((TextView)findViewById(R.id.historicalTitle)).setText(historicalDataStr);
        }
    };
    
    
    private void startWMSS () 
    {
    	if (null == wms)
    	{
    		wms = new WiFiMappingSystem(this);
    		wms.subscribe(this);
    	}
    	
    	wms.map();
    	
    	// call mapping function TBD
    	//mWMSSubscriber.subscribe(this); TBD
    }
    
    
    private void stopWMSS () 
    {
    	wms.stopMapping();
    }
    
    
    private void startWPSS () 
    {
    	
    	if (null == wms)
    	{
    		wps = new WiFiPositioningSystem(this);
    		wps.subscribe(this);
    	}
    	
    	wps.startPositioning();
    	
    	// call positioning function TBD
    	// if positioning function start returns error (if no mapping data is present) display toast
    	// also display historical data of last known location
    	/*
    	    Context context = getApplicationContext();
    	 	int duration = Toast.LENGTH_SHORT;
        	Toast toast;
        	CharSequence toastText = null;
        	toastText = "No mapped data exists.  Click Start Mapping Button.";
        	toast = Toast.makeText(context, toastText, duration);
        	toast.show();
        	
        	positionData tmpPositionData = WPSS.getHistoricalData();
    	 */
    	//else no error
    	//mWPSSSubscriber.subscribe(this); TBD
    }
    
    
    private void stopWPSS () 
    {
    	wps.stopPositioning();

    }
    /*TBD Uncomment when classes are available
    public update(List<PositionData> posData){
    	// if posData.NoError() TBD
    	positionDATA.add(posData.toString());
    	((TextView)findViewById(R.id.currentData)).setText(posData.toString());
    	
    	// else position cannot be determined w/ current WAP
    	Context context = getApplicationContext();
	 	int duration = Toast.LENGTH_SHORT;
    	Toast toast;
    	CharSequence toastText = null;
    	toastText = "Cannot determine position based on stored WAP Data.";
    	toast = Toast.makeText(context, toastText, duration);
    	toast.show();
    	
    	positionData tmpPositionData = WPSS.getHistoricalData();
    }
    public update(List<MapData> mapData){
    	positionDATA.add(MapData.toString());
    	((TextView)findViewById(R.id.currentData)).setText(MapData.GPStoString());
    }*/
    
    
    public void update(MapData mapData)
    {
    	if(null != mapData.getScanResults())
    	{
    		List<ScanResult> scanResults = mapData.getScanResults();
    		if (scanResults.isEmpty())
			{
    			// TODO: Magic handle (and should this be setting the other field?
    			((TextView)findViewById(R.id.currentData)).setText("No Data Available");
			}
    		else
    		{
    			// Set location value
    			// TODO: Magic handle
    			Location location = mapData.getLocation();
    			if (null != location)
    			{
    				((TextView)findViewById(R.id.currentData)).setText(location.getLatitude() + " " + location.getLongitude());
    			}
    			
    			
	    		positionData.clear();
		    	for (ScanResult scanResult: mapData.getScanResults())
		    	{
		    		positionData.add(scanResult.BSSID + " " + scanResult.level);
		    	}
		    	
		    	mlistAdapter.notifyDataSetChanged();
    		}
    	}
    }

    
    // --- WPS Update method
    public void update(List<PositionData> positionData)
    {
    	//TODO
    	Toast toast;
    	int duration = Toast.LENGTH_SHORT;
    	Context context = getApplicationContext();
    	toast = Toast.makeText(context, "WPS UPDATE CALLED!", duration);
    	toast.show();
    }
    
}